import router from './router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import pinia from './store'
import useUserStore from './store/modules/user'
import setting from './setting'
nprogress.configure({ showSpinner: false })

let userStore = useUserStore(pinia)
router.beforeEach(async (to, from, next) => {
  // to and from are both route objects. must call `next`.
  document.title = `${setting.title} - ${to.meta.title}`
  nprogress.start()
  let token = userStore.token
  let username = userStore.username
  if (token) {
    if (to.path == '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        try {
          await userStore.userInfo()
          next()
        } catch (error) {
          await userStore.userLogout()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path == '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
  next()
})
router.afterEach((to, from, failure) => {
  nprogress.done()
})
//全部路由组件：登入||404||任意路由（404）||首页||数据大屏||权限管理（三个子路由）||权限管理（四个子路由）
